package edu.hawaii.myisern.model;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * A helper class to convert between String and list.
 * 
 * @author Edward Kim
 * @author JianFei Liao
 * @author KaYee Leung
 */
public class ListStringConverter {
  /**
   * Converts a list of String to a String with commas.
   * 
   * @param listElements The list to convert.
   * @return A String.
   */
  public String listToString(List<String> listElements) {
    int listSize = listElements.size();
    int listCount = 1;
    StringBuffer listString = new StringBuffer();
    for (String element : listElements) {
      if (listCount < listSize) {
        element += ", ";
      }
      listString.append(element);
      listCount++;
    }
    
    return listString.toString();
  }
  
  /**
   * Converts a String with commas to a list of String.
   * 
   * @param string The String to convert.
   * @return A list of String.
   */
  public List<String> stringToList(String string) {
    List<String> list = new ArrayList<String>();
    if (string == null) {
      return list;
    }
    
    String copy = string;
    String part = "";

    while (copy.contains(",")) {
      int stopIndex = copy.indexOf(',');
      part = copy.substring(0, stopIndex);
      copy = copy.substring(stopIndex + 1);
      list.add(part.trim());
    }
    list.add(copy.trim());
    
    return list;
  }
  
  /**
   * Converts a list of BigInteger to a String with commas.
   * 
   * @param yearsList The list to convert.
   * @return A String.
   */
  public String bigIntegerListToString(List<BigInteger> yearsList) {
    int listSize = yearsList.size();
    int listCount = 1;
    StringBuffer years = new StringBuffer();
    for (BigInteger year : yearsList) {
      years.append(year.toString());
      if (listCount < listSize) {
        String separator = ", ";
        years.append(separator);
      }
      listCount++;
    }

    return years.toString();
  }
  
  /**
   * Converts a String with commas to a list of BigInteger.
   * 
   * @param yearsListString The String to convert.
   * @throws NumberFormatException If errors happen.
   * @return A list of BigInteger.
   */
  public List<BigInteger> stringToBigIntegerList(String yearsListString) 
      throws NumberFormatException {
    List<BigInteger> list = new ArrayList<BigInteger>();
    if ((yearsListString == null) || ("".equals(yearsListString))) {
      return list;
    }
    String copy = yearsListString;
    String part = "";
    BigInteger year = null;
    while (copy.contains(",")) {
      int stopIndex = copy.indexOf(',');
      part = copy.substring(0, stopIndex);
      copy = copy.substring(stopIndex + 1);
      year = new BigInteger(part.trim());
      list.add(year);
    }
    year = new BigInteger(copy.trim());
    list.add(year);

    return list;
  }
}